package com.epay.epay.util;

import java.security.MessageDigest;
import java.util.Map;  
import java.util.TreeMap;  
  
public class MD5Signer {  
  
    /**  
     * 生成MD5签名  
     * @param params 参与签名的参数  
     * @param key 商户密钥  
     * @return 生成的MD5签名  
     */  
    public static String generateMD5Sign(Map<String, String> params, String key) {  
        // 使用TreeMap对参数按键进行排序  
        Map<String, String> sortedParams = new TreeMap<>();  
        for (Map.Entry<String, String> entry : params.entrySet()) {  
            String keyName = entry.getKey();  
            String value = entry.getValue();  
            // 过滤空值和sign、sign_type参数  
            if (value != null && !keyName.equals("sign") && !keyName.equals("sign_type")) {  
                sortedParams.put(keyName, value);  
            }  
        }

        System.out.println(sortedParams);
        // 构建排序后的查询字符串  
        StringBuilder query = new StringBuilder();  
        sortedParams.forEach((k, v) -> query.append(k).append("=").append(v).append("&"));  
        if (query.length() > 0) {  
            query.deleteCharAt(query.length() - 1); // 去掉最后一个&  
        }


        // 拼接商户密钥  
        query.append(key);

        System.out.println(query);

        // 进行MD5签名  
        return md5(query.toString());  
    }  
  
    /**  
     * MD5加密  
     * @param content 待加密的内容  
     * @return MD5加密后的字符串  
     */  
    private static String md5(String content) {  
        try {  
            MessageDigest md = MessageDigest.getInstance("MD5");  
            byte[] digest = md.digest(content.getBytes());  
            StringBuilder hexStr = new StringBuilder();  
            String shaHex;  
            for (byte b : digest) {  
                shaHex = Integer.toHexString(b & 0xFF);  
                if (shaHex.length() < 2) {  
                    hexStr.append(0);  
                }  
                hexStr.append(shaHex);  
            }  
            return hexStr.toString();  
        } catch (Exception e) {  
            e.printStackTrace();  
            return "";  
        }  
    }  
  
    public static void main(String[] args) {  
        Map<String, String> params = new TreeMap<>();  
        params.put("a", "1");  
        params.put("b", "2");  
        params.put("c", "3");  
        params.put("sign", "ignore");  
        params.put("sign_type", "ignore");  
        params.put("d", "");  
  
        String key = "mySecretKey";  
        String sign = generateMD5Sign(params, key);  
        System.out.println("Generated MD5 Sign: " + sign);  
    }  
}